package cn.liyicun.test.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.system.SystemUtil;
import cn.liyicun.test.base.Common;
import cn.liyicun.test.service.UserFileService;
import cn.liyicun.test.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class MainController {

    @Value("${server.port:8080}")
    int port;

    @Autowired
    UserService user;
    @Autowired
    UserFileService ufile;

    @RequestMapping("/main")
    public String main(HttpServletRequest req, HttpServletResponse res, Model model, @RequestParam(value = "order", required = false, defaultValue = "id") String order
            , @RequestParam(value = "catid", required = false, defaultValue = "0") Integer catid
    ) throws IOException {
//        HttpSession session = req.getSession();
//        if (session == null || session.getAttribute(Common.USER_SESSION_NAME) == null) {
//            res.sendRedirect("/");
//            return null;
//        }


        String orderby = "id  desc";
        if ("view".equals(order)) {
            orderby = " view_count  desc";
        }
        if ("like".equals(order)) {
            orderby = " like_count  desc";
        }
        String where = "";
        if (catid == 1 || catid == 2) {
            where = " and catid=" + catid;
        }

        List<Map<String, Object>> list = ufile.squareFileList(where, orderby, 0, 500);

        if("id".equals(order)) {
            Collections.shuffle(list);
        }
        model.addAttribute("lists", list);

        return "main";
    }

}